﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ClassLibrary;
using Forms.UserControls;
using Google.Protobuf.WellKnownTypes;
using Sunny.UI;
using ClassLibrary.Service;
using Forms.UserController;
using System.Diagnostics;
using Org.BouncyCastle.Crypto.Agreement.JPake;
using System.Drawing.Imaging;
using System.Threading.Tasks;

namespace Forms
{
    public partial class ChatForm : UIForm
    {
        User me;
        User receiver;
        // 发送者和接收者头像
        Image senderImage, receiverImage;
        public ChatForm(User me, User receiver)
        {
            SetStyle(
                ControlStyles.UserPaint//使用自定义的绘制方式
                | ControlStyles.ResizeRedraw//当控件大小发生变化时就重新绘制
                | ControlStyles.DoubleBuffer// 双缓冲
                | ControlStyles.SupportsTransparentBackColor//则控件接受 alpha 组件数小于 255 个的 BackColor 来模拟透明度
                | ControlStyles.AllPaintingInWmPaint//禁止擦除背景.则控件忽略窗口消息 WM_ERASEBKGND 以减少闪烁
                | ControlStyles.EnableNotifyMessage// 
                                                   // Enable the OnNotifyMessage event so we get a chance to filter out 
                                                   // Windows messages before they get to the form's WndProc
                | ControlStyles.OptimizedDoubleBuffer//则控件将首先绘制到缓冲区而不是直接绘制到屏幕，这可以减少闪烁
                , true);
            InitializeComponent();
            panelMessage.AutoScroll = true;
            this.me = me;
            this.receiver = receiver;
            senderImage = ImageService.BytesToImage(ImageService.getProfileByID(me.UserID));
            receiverImage = ImageService.BytesToImage(ImageService.getProfileByID(receiver.UserID));
            this.Text = receiver.UserName;
            Color userColor = MainForm.MainForm.userColor;
            UIStyles.InitColorful(userColor, Color.White);
        }
        /// <summary>
        /// 当前消息气泡起始位置
        /// </summary>
        private int _top = 0;

        /// <summary>
        /// 当前消息气泡高度
        /// </summary>
        private int _height = 0;

        /// <summary>
        /// 显示接收消息
        /// </summary>
        /// <param name="content">接收内容</param>
        private void ShowReceiveMessage(string content)
        {
            UC_MsgItem item = new UC_MsgItem
            {
                messageType = UC_MsgItem.MessageType.Receive,
                senderImage = senderImage,
                receiverImage = receiverImage
            };
            item.SetInteractionContent(content);

            //计算高度
            item.Top = _top + _height;
            item.Left = 15;

            _top = item.Top;
            _height = item.HEIGHT;

            //滚动条移动最上方，重新计算气泡在panel的位置
            panelMessage.AutoScrollPosition = new Point(0, 0);
            panelMessage.Controls.Add(item);
        }

        /// <summary>
        /// 显示接收图片
        /// </summary>
        /// <param name="image">接收图片</param>
        private void ShowReceiveImage(Image image)
        {
            UC_MsgItem item = new UC_MsgItem
            {
                messageType = UC_MsgItem.MessageType.Receive,
                senderImage = senderImage,
                receiverImage = receiverImage
            };
            image = ResizeImage(image);
            item.SetInteractionImage(image);

            //计算高度
            item.Top = _top + _height;
            item.Left = 15;

            _top = item.Top;
            _height = item.HEIGHT;
            //滚动条移动最上方，重新计算气泡在panel的位置
            panelMessage.AutoScrollPosition = new Point(0, 0);
            panelMessage.Controls.Add(item);
        }

        /// <summary>
        /// 更新界面，显示发送消息
        /// </summary>
        private async void AddSendMessage(string content)
        {
            #region 发送消息持久化
            Interaction input = new Interaction
            {
                InteractionID = Guid.NewGuid().ToString(),
                InteractionContent = content,
                InteractionSenderID = me.UserID,
                InteractionReceiverID = receiver.UserID,
                InteractionTime = DateTime.Now,
                InteractionStatus = false,
                InteractionType = "text"
            };
            InteractionService interactionService = new InteractionService();
            interactionService.AddInteraction(input);
            #endregion

            #region 追加气泡

            UC_MsgItem item = new UC_MsgItem
            {
                messageType = UC_MsgItem.MessageType.Send,
                senderImage = senderImage,
                receiverImage = receiverImage
            };
            item.SetInteractionContent(content);

            item.Top = _top + _height;
            item.Left = this.Width - 92 - item.WIDTH;

            _top = item.Top;
            _height = item.HEIGHT;
            panelMessage.AutoScrollPosition = new Point(0, 0);
            panelMessage.Controls.Add(item);

            #endregion
        }

        /// <summary>
        /// 更新界面，显示发送图片
        /// </summary>
        private async void AddSendImage(Image image)
        {
            #region 发送消息持久化
            // 初始化发送消息
            Interaction input = new Interaction
            {
                InteractionID = Guid.NewGuid().ToString(),
                InteractionImage = ImageService.ImageToBytes(image),
                InteractionSenderID = me.UserID,
                InteractionReceiverID = receiver.UserID,
                InteractionTime = DateTime.Now,
                InteractionStatus = false,
                InteractionType = "image"
            };
            InteractionService interactionService = new InteractionService();
            interactionService.AddInteraction(input);
            #endregion

            #region 追加气泡

            UC_MsgItem item = new UC_MsgItem
            {
                messageType = UC_MsgItem.MessageType.Send,
                senderImage = senderImage,
                receiverImage = receiverImage
            };
            // 调整图片大小
            image = ResizeImage(image);
            item.SetInteractionImage(image);

            item.Top = _top + _height;
            item.Left = this.Width - 92 - item.WIDTH;

            _top = item.Top;
            _height = item.HEIGHT;
            panelMessage.AutoScrollPosition = new Point(0, 0);
            panelMessage.Controls.Add(item);

            #endregion
        }

        /// <summary>
        /// 更新界面，初始化显示发送消息
        /// </summary>
        private void ShowSendMessage(string content)
        {
            UC_MsgItem item = new UC_MsgItem
            {
                messageType = UC_MsgItem.MessageType.Send,
                senderImage = senderImage,
                receiverImage = receiverImage
            };
            item.SetInteractionContent(content);

            item.Top = _top + _height;
            item.Left = this.Width - 92 - item.WIDTH;

            _top = item.Top;
            _height = item.HEIGHT;
            panelMessage.AutoScrollPosition = new Point(0, 0);
            panelMessage.Controls.Add(item);
        }

        /// <summary>
        /// 更新界面，初始化显示发送图片
        /// </summary>
        private void ShowSendImage(Image image)
        {
            UC_MsgItem item = new UC_MsgItem
            {
                messageType = UC_MsgItem.MessageType.Send,
                senderImage = senderImage,
                receiverImage = receiverImage
            };
            image = ResizeImage(image);
            item.SetInteractionImage(image);

            item.Top = _top + _height;
            item.Left = this.Width - 92 - item.WIDTH;

            _top = item.Top;
            _height = item.HEIGHT;
            panelMessage.AutoScrollPosition = new Point(0, 0);
            panelMessage.Controls.Add(item);
        }

        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            if (tbMsg.Text == "" || tbMsg.Text == null) return;
            // 全局变量改变，主界面刷新
            FlashVariables.GlobalVariable++;
            AddSendMessage(tbMsg.Text);
            panelMessage.AutoScrollPosition = new Point(0, this._top);
            tbMsg.Clear();
        }

        private void UC_MessageContainer_Load(object sender, EventArgs e)
        {
            // 查找两人之间的消息
            List<Interaction> interactions = InteractionService.GetInteractionsBySenderAndReceiver(me.UserID, receiver.UserID);
            // 根据 Name 属性进行排序  
            interactions.Sort((a, b) => a.InteractionTime.CompareTo(b.InteractionTime));
            var selfNumber = me.UserID;
            // 遍历聊天记录
            foreach (var item in interactions)
            {
                // 消息image和content内容处理函数
                if (item.InteractionSenderID.Equals(selfNumber))
                {
                    if (item.InteractionType == "text")
                    {
                        ShowSendMessage(item.InteractionContent);
                    }
                    else
                    {
                        ShowSendImage(ImageService.BytesToImage(item.InteractionImage));
                    }
                }
                else
                {
                    if (item.InteractionType == "text")
                    {
                        ShowReceiveMessage(item.InteractionContent);
                    }
                    else
                    {
                        ShowReceiveImage(ImageService.BytesToImage(item.InteractionImage));
                    }
                }
            }
        }

        private void Emoji_Click(object sender, EventArgs e)
        {
            //获取按钮在屏幕上的位置
            Point emojiButtonScreenPos = Emoji.PointToScreen(Point.Empty);
            Emoji emoji = new Emoji(emojiButtonScreenPos.X, emojiButtonScreenPos.Y);
            emoji.Show();
            // 添加事件处理程序
            emoji.EmojiSelected += Emoji_EmojiSelected;
        }

        private void Emoji_EmojiSelected(object sender, Image selectedEmoji)
        {
            if (selectedEmoji != null)
            {
                AddSendImage(selectedEmoji);
                panelMessage.AutoScrollPosition = new Point(0, this._top);
            }
        }

        //设置表情包的显示在textbox中的大小
        private Image ResizeImage(Image img)
        {
            // 计算缩小比例，比如这里设定最大宽度为300
            int maxWidth = 100;
            double ratio = (double)maxWidth / img.Width;
            int newWidth = maxWidth;
            int newHeight = (int)(img.Height * ratio);

            Image result = img.ResizeImage(newWidth, newHeight);
            //result.RawFormat = ImageFormat.Png;

            return result;
        }

        private void tbMsg_TextChanged(object sender, EventArgs e)
        {

        }

        private void Document_Click(object sender, EventArgs e)
        {
            //用户选择要发送的文件
            string filepath = string.Empty;
            OpenFileDialog selsectFile = new OpenFileDialog();
            selsectFile.Multiselect = false;//设置是否可以多选
            selsectFile.Title = "请选择要发送的文件";//窗口title
            selsectFile.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.gif;*.bmp";//筛选文本文件，默认所有
            if (selsectFile.ShowDialog() == DialogResult.OK)
            {
                filepath = selsectFile.FileName;
            }

            // 将图片文件加载到 RichTextBox 控件中
            if (!string.IsNullOrEmpty(filepath))
            {
                // 将图片文件拷贝到剪贴板
                System.Drawing.Image img = System.Drawing.Image.FromFile(filepath);

                AddSendImage(img);
                panelMessage.AutoScrollPosition = new Point(0, this._top);
            }
        }

        // 异步方法打开地图
        private async Task OpenHtmlMapAsync(string htmlFilePath)
        {
            // 异步执行地图打开操作
            await Task.Run(() =>
            {
                ProcessStartInfo processStartInfo = new ProcessStartInfo(htmlFilePath);
                Process process = new Process();
                process.StartInfo = processStartInfo;
                process.StartInfo.UseShellExecute = true;
                process.Start();
            });
        }

        // 地图按钮点击事件处理器
        private async void Map_ClickAsync(object sender, EventArgs e)
        {
            // 相对于应用程序启动路径的相对路径
            string relativePath = @"..\..\..\Map\map.html";
            string htmlFilePath = " ";

            try
            {
                // 获取应用程序的启动路径
                string appStartupPath = AppDomain.CurrentDomain.BaseDirectory;

                // 合并启动路径和相对路径
                htmlFilePath = Path.GetFullPath(Path.Combine(appStartupPath, relativePath));

                // 调用异步方法打开地图
                await OpenHtmlMapAsync(htmlFilePath);
            }
            catch (Exception ex)
            {
                // 显示错误消息
                UIMessageBox.Show("Error opening HTML file: " + ex.Message);
            }
        }

    }
}
